package com.cyy.demo.service.impl;

import com.cyy.demo.common.Result;
import com.cyy.demo.entity.User;
import com.cyy.demo.dao.UserMapper;
import com.cyy.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 对于不经常改动的类容，可以在查询的时候缓存下来，在增删改的时候删除
 */

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    @Cacheable(value = "user", key = "#p0")
    public Result findUser(int id) {
        User user = userMapper.selectByPrimaryKey(id);
        LOGGER.info("info:{}", user.toString());

        if (user == null) {
            return new Result("没有用户");
        }
        return new Result(user);
    }

    @Override
    @Cacheable(value = "user")
    public Result findUsers() {
        List<User> users = userMapper.selectAll();
        Result result = new Result();
        result.setData(users);
        return result;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "user", allEntries = true)
    public void saveUser(User user) {
         User newUser = userMapper.insert(user);
    }

    @Override
    @Cacheable(value ="user",key ="#username")
    public Result findUser(String username) {
        LOGGER.debug("findUser,{}",username);
        LOGGER.info("findUser,{}",username);
        return new Result(userMapper.selectByUsername(username));

    }

    /**
     * 执行方法后删除user缓存
     * @param id
     */
    @Override
    @CacheEvict(value = "user", allEntries = true)
    public void remove(int id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
//    @CachePut(cacheNames = "user", key = "#p0.id")
    @CacheEvict(value = "user", allEntries = true)
    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<User> users){
        userMapper.insertBatch(users);
    }


}
